<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/6/18
 * Time: 16:17
 */
namespace common\compents;

use common\models\Http;
use common\msg\UserMsg;
use yii\base\Behavior;
use yii\base\Controller;

class LoginBehavior extends Behavior{

    //加载的默认地址
    public $url = '/';

    /**
     * @inheritdoc
     */
    public function attach($owner)
    {
        $this->owner = $owner;
        $owner->on(Controller::EVENT_BEFORE_ACTION, [$this, 'beforeFilter']);
    }

    /**
     * @inheritdoc
     */
    public function detach()
    {
        if ($this->owner) {
            $this->owner->off(Controller::EVENT_BEFORE_ACTION, [$this, 'beforeFilter']);
            $this->owner = null;
        }
    }

    public function beforeFilter(){
        $userInfo = Http::session('user');
        if($userInfo){
            $request = \Yii::$app->request;
            if($request->isAjax){
                $error['status'] = 1;
                $error['msg'] = UserMsg::$alread_login;
                exit(json_encode($error));
            }
            else{
                header("location:{$this->url}");exit;
            }
        }
    }
}